import React, { memo } from 'react';
import _ from 'lodash';
import { Tooltip, Popover, Dropdown, Menu, Checkbox } from 'antd';
import {
  SyncOutlined,
  ColumnHeightOutlined,
  SettingOutlined,
  HolderOutlined,
  VerticalAlignTopOutlined,
  VerticalAlignMiddleOutlined,
  VerticalAlignBottomOutlined,
} from '@ant-design/icons';
import { arrayMoveImmutable } from 'array-move';
import DebounceWrapper from '@/components/DebounceWrapper';
import { SortableContainer, SortableElement, SortableHandle } from 'react-sortable-hoc';
import styles from './tableHeaderTools.less';

export const tableSizeList = [
  { key: 'default', label: '默认' },
  { key: 'middle', label: '中等' },
  { key: 'small', label: '紧凑' },
];

const SortableIcon = SortableHandle(HolderOutlined);
const SortableListItem = SortableElement((props) => (
  <div {...props} className={styles.rowListItem} />
));
const SortableListContainer = SortableContainer((props) => (
  <div {...props} className={styles.rowListContainer} />
));

const ColumnSetting = memo(
  ({ columnSettings, setColumnSettings }) => {
    const { leftColumns, middleColumns, rightColumns } = columnSettings;

    // 切换固定状态
    const handleChangeFixed = ({ key, prevFixed, nextFixed }) => {
      setColumnSettings((prevSettings) => {
        const { leftColumns, middleColumns, rightColumns } = prevSettings;
        const mappings = [
          { fixed: 'left', list: leftColumns },
          { fixed: false, list: middleColumns },
          { fixed: 'right', list: rightColumns },
        ];
        const deleteFromPrevList = () => {
          const currentList = _.find(mappings, ({ fixed }) => fixed === prevFixed)?.list;
          if (currentList) {
            const index = _.findIndex(currentList, ({ key: itemKey }) => itemKey === key);
            if (index > -1) {
              return currentList.splice(index, 1);
            }
          }
        };
        const insertNextListAndSort = (item) => {
          const targetList = _.find(mappings, ({ fixed }) => fixed === nextFixed)?.list;
          if (targetList) {
            if (!nextFixed) {
              if (prevFixed === 'left') {
                targetList.unshift(item);
              } else if (prevFixed === 'right') {
                targetList.push(item);
              }
            } else {
              const currentOriginalIndex = item.originalIndex;
              const targetOriginalIndexList = _.map(targetList, 'originalIndex');
              const index = _.findIndex(
                targetOriginalIndexList,
                (originIndex) => originIndex > currentOriginalIndex,
              );
              if (index > -1) {
                targetList.splice(index, 0, item);
              } else {
                targetList.push(item);
              }
            }
          }
        };
        const [columnItem] = deleteFromPrevList() || [];
        if (columnItem) {
          insertNextListAndSort(columnItem);
        }
        return { leftColumns, middleColumns, rightColumns };
      });
    };

    // 切换展示状态
    const handleChangeChecked = ({ key, checked, fixed }) => {
      setColumnSettings((prevSettings) => {
        const { leftColumns, middleColumns, rightColumns } = prevSettings;
        const mappings = [
          { fixed: 'left', list: leftColumns },
          { fixed: false, list: middleColumns },
          { fixed: 'right', list: rightColumns },
        ];
        const targetList = _.find(
          mappings,
          ({ fixed: currentFixed }) => currentFixed === fixed,
        )?.list;
        if (targetList) {
          const index = _.findIndex(targetList, ({ key: currentKey }) => currentKey === key);
          if (index > -1) {
            const [item] = targetList.splice(index, 1);
            item.checked = checked;
            targetList.splice(index, 0, item);
          }
        }
        return { leftColumns, middleColumns, rightColumns };
      });
    };

    return (
      <div className={styles.toolColumnSettingContainer}>
        {!!leftColumns.length && (
          <div className={styles.columnSettingContentList}>
            <span className={styles.columnSettingContentTitle}>固定在列首</span>
            <div className={styles.rowListContainer}>
              {leftColumns.map(({ title, key, checked }) => (
                <div key={key} className={styles.rowListItem} title={title}>
                  <Checkbox
                    checked={checked}
                    onChange={(e) => {
                      handleChangeChecked({ key, checked: e.target.checked, fixed: 'left' });
                    }}
                  >
                    {title}
                    <div className={styles.rowListItemIcon}>
                      <Tooltip placement="top" title="不固定">
                        <span
                          className={styles.rowListItemIconItem}
                          onClick={(e) => {
                            e.preventDefault();
                            handleChangeFixed({ key, prevFixed: 'left', nextFixed: false });
                          }}
                        >
                          <VerticalAlignMiddleOutlined />
                        </span>
                      </Tooltip>
                      <Tooltip placement="top" title="固定在列尾">
                        <span
                          className={styles.rowListItemIconItem}
                          onClick={(e) => {
                            e.preventDefault();
                            handleChangeFixed({ key, prevFixed: 'left', nextFixed: 'right' });
                          }}
                        >
                          <VerticalAlignBottomOutlined />
                        </span>
                      </Tooltip>
                    </div>
                  </Checkbox>
                </div>
              ))}
            </div>
          </div>
        )}
        {!!middleColumns.length && (
          <div className={styles.columnSettingContentList}>
            <span className={styles.columnSettingContentTitle}>非固定列</span>
            <SortableListContainer
              useDragHandle
              disableAutoscroll
              helperClass="common-table-column-dragging"
              onSortEnd={({ oldIndex, newIndex }) => {
                if (oldIndex !== newIndex) {
                  const nextMiddleColumns = arrayMoveImmutable(
                    middleColumns.slice(),
                    oldIndex,
                    newIndex,
                  ).filter((item) => !!item);
                  setColumnSettings(({ leftColumns, rightColumns }) => ({
                    leftColumns,
                    middleColumns: nextMiddleColumns,
                    rightColumns,
                  }));
                }
              }}
            >
              {middleColumns.map(({ title, key, checked }, index) => (
                <SortableListItem key={key} index={index} title={title}>
                  <SortableIcon />
                  <Checkbox
                    checked={checked}
                    onChange={(e) => {
                      handleChangeChecked({ key, checked: e.target.checked, fixed: false });
                    }}
                  >
                    {title}
                    <div className={styles.rowListItemIcon}>
                      <Tooltip placement="top" title="固定在列首">
                        <span
                          className={styles.rowListItemIconItem}
                          onClick={(e) => {
                            e.preventDefault();
                            handleChangeFixed({ key, prevFixed: false, nextFixed: 'left' });
                          }}
                        >
                          <VerticalAlignTopOutlined />
                        </span>
                      </Tooltip>
                      <Tooltip placement="top" title="固定在列尾">
                        <span
                          className={styles.rowListItemIconItem}
                          onClick={(e) => {
                            e.preventDefault();
                            handleChangeFixed({ key, prevFixed: false, nextFixed: 'right' });
                          }}
                        >
                          <VerticalAlignBottomOutlined />
                        </span>
                      </Tooltip>
                    </div>
                  </Checkbox>
                </SortableListItem>
              ))}
            </SortableListContainer>
          </div>
        )}
        {!!rightColumns.length && (
          <div className={styles.columnSettingContentList}>
            <span className={styles.columnSettingContentTitle}>固定在列尾</span>
            <div className={styles.rowListContainer}>
              {rightColumns.map(({ title, key, checked }) => (
                <div key={key} className={styles.rowListItem} title={title}>
                  <Checkbox
                    checked={checked}
                    onChange={(e) => {
                      handleChangeChecked({ key, checked: e.target.checked, fixed: 'right' });
                    }}
                  >
                    {title}
                    <div className={styles.rowListItemIcon}>
                      <Tooltip placement="top" title="固定在列首">
                        <span
                          className={styles.rowListItemIconItem}
                          onClick={(e) => {
                            e.preventDefault();
                            handleChangeFixed({ key, prevFixed: 'right', nextFixed: 'left' });
                          }}
                        >
                          <VerticalAlignTopOutlined />
                        </span>
                      </Tooltip>
                      <Tooltip placement="top" title="不固定">
                        <span
                          className={styles.rowListItemIconItem}
                          onClick={(e) => {
                            e.preventDefault();
                            handleChangeFixed({ key, prevFixed: 'right', nextFixed: false });
                          }}
                        >
                          <VerticalAlignMiddleOutlined />
                        </span>
                      </Tooltip>
                    </div>
                  </Checkbox>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    );
  },
  (prevProps, nextProps) => prevProps.columnSettings === nextProps.columnSettings,
);

export default memo(
  ({ loading, tableSize, setTableSize, columnSettings, setColumnSettings, handleRefresh }) => {
    const RefreshButton = DebounceWrapper(() => (
      <span
        className={styles.toolItem}
        onClick={() => {
          handleRefresh && handleRefresh();
        }}
      >
        <SyncOutlined spin={loading} />
      </span>
    ));

    return (
      <div className={styles.toolList}>
        <Tooltip placement="top" title="刷新">
          <RefreshButton />
        </Tooltip>
        <Tooltip placement="top" title="密度">
          <Dropdown
            trigger="click"
            placement="bottom"
            overlay={
              <Menu
                items={tableSizeList}
                selectedKeys={[tableSize]}
                className={styles.toolMenuSelect}
                onClick={({ key }) => {
                  if (key !== tableSize) {
                    setTableSize(key);
                  }
                }}
              />
            }
          >
            <span className={styles.toolItem}>
              <ColumnHeightOutlined />
            </span>
          </Dropdown>
        </Tooltip>
        <Tooltip placement="top" title="列设置">
          <Popover
            trigger="click"
            placement="bottomRight"
            content={
              <ColumnSetting
                columnSettings={columnSettings}
                setColumnSettings={setColumnSettings}
              />
            }
          >
            <span className={styles.toolItem}>
              <SettingOutlined />
            </span>
          </Popover>
        </Tooltip>
      </div>
    );
  },
  (prevProps, nextProps) =>
    prevProps.loading === nextProps.loading &&
    prevProps.tableSize === nextProps.tableSize &&
    prevProps.columnSettings === nextProps.columnSettings,
);
